package com.cskaoyan.controller;

import com.cskaoyan.annotation.AdminLog;
import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.InfoBean;
import com.cskaoyan.bean.basebean.BaseRespVo;
import com.cskaoyan.bean.basebean.DataBean;
import com.cskaoyan.exception.LoginFailException;
import com.cskaoyan.service.AdminService;
import com.cskaoyan.shiro.MallToken;
import com.cskaoyan.utils.Md5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("admin/auth")
public class AuthController {
    @Autowired
    AdminService adminService;

    @AdminLog(action = "登录")
    @RequestMapping("login")
    public BaseRespVo login(@RequestBody Map map, HttpServletRequest request) throws LoginFailException {

//        String username = (String) map.get("username");
//        String password = (String) map.get("password");
//        //执行登录业务，并且响应结果
//        //登录业务先略，Shiro框架之后写这部分业务
//
//        DataBean dataBean = new DataBean();
//        DataBean.AdminInfoBean adminInfo = new DataBean.AdminInfoBean();
//        adminInfo.setAvatar("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white-d0c9fe2af5.png");
//        adminInfo.setNickName("admin123");
//        dataBean.setAdminInfo(adminInfo);
//        //token是sessionId
//        dataBean.setToken("587e315d-0ac3-47a0-9857-7e625ce866ee");
//        return BaseRespVo.ok(dataBean);

        //改用Shiro框架

        Subject subject = SecurityUtils.getSubject();

        String username = (String) map.get("username");
        String password = (String) map.get("password");
        try {
            password = Md5Utils.getMd5(password, "password");
            MallToken adminToken = new MallToken(username, password, "admin");

//            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            subject.login(adminToken);
            //subject.login(usernamePasswordToken);
            //subject.login → 认证 → Authenticator执行认证 → realm的doGetAuthenInfo
            //可以获得认证状态
            //boolean authenticated = subject.isAuthenticated();
//        获得用户信息 → realm里的doGetAuthenInfo中的构造的Principal信息
            //Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();
        } catch (Exception e) {
            //e.printStackTrace();
            throw new LoginFailException();
        }

        //登录成功
//        HttpSession session = request.getSession();
//        session.setAttribute("username",username);
        DataBean dataBean = new DataBean();
        DataBean.AdminInfoBean adminInfoBean = new DataBean.AdminInfoBean();
        Admin admin = adminService.selectAdminByUsername(username);
        adminInfoBean.setAvatar(admin.getAvatar());
        adminInfoBean.setNickName(admin.getUsername());
        dataBean.setAdminInfo(adminInfoBean);
        dataBean.setToken(((String) subject.getSession().getId()));
        System.out.println(subject.isAuthenticated());
        String ip = request.getRemoteAddr();
        //如果是本地访问则将ip修改为127.0.0.1
        ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
        adminService.updateAdminLastLoginIp(admin.getId(), ip);
        return BaseRespVo.ok(dataBean);
    }


    @RequestMapping("info")
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        //boolean authenticated = subject.isAuthenticated();
        Serializable sessionId = subject.getSession().getId();
        //查询用户信息
        //来源于数据库
        //token是用于获得用户信息，来源于Shiro
        //先假定一个用户id来做其他信息的查询

        Admin admin = (Admin) subject.getPrincipals().getPrimaryPrincipal();
        //Admin admin = adminService.selectAdminByUsername(username);
        InfoBean infoBean = new InfoBean();

//        infoBean.setAvatar("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white-d0c9fe2af5.png");
//        infoBean.setName("admin123");
//        ArrayList<String> perms = new ArrayList<>();
//        perms.add("*");
//        infoBean.setPerms(perms);
//        ArrayList<String> roles = new ArrayList<>();
//        roles.add("超级管理员");
//        infoBean.setRoles(roles);


        infoBean.setAvatar(admin.getAvatar());
        infoBean.setName(admin.getUsername());
        List<String> permissions = adminService.selectSysPermissionByUserName(admin.getUsername());
        infoBean.setPerms(permissions);
        List<String> roles = adminService.selectRolesByUsername(admin.getUsername());
        infoBean.setRoles(roles);
        return BaseRespVo.ok(infoBean);

    }

    @AdminLog(action = "退出")
    @RequestMapping("logout")
    public BaseRespVo logout() {
//        Subject subject = SecurityUtils.getSubject();
//        if(subject == null) {
//            return BaseRespVo.fail("用户未登录或登录已失效");
//        }
//        subject.logout();
        return BaseRespVo.ok();
    }
}
